package com.wan.commonsdk;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sourceforge.simcpux.Util;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.reyun.sdk.ReYunTrack;
import com.wan.activity.LoginActivity;
import com.wan.activity.Pay_Order_Activity;
import com.wan.activity.guest_userbind;
import com.wan.activity.usermanager;
import com.wanew.activity.WANLoginDialogActivity;

public class WanCommonSdk {
	public static LoginCompleCallback loginCallBack;
	public static PayupCompleteCallBack payupcallBack;
	private static WanCommonSdk commonsdk = null;
	public static int screen_orientation = 0;
	public static final int SCREEN_ORIENTATION_PORTRAIT = 0;
	public static final int SCREEN_ORIENTATION_LANDSCAPE = 1;
	public static final int SCREEN_ORIENTATION_AUTO = 2;
	public static final int MAX_USERNAME_LENGTH = 20;
	public static final int MIN_USERNAME_LENGTH = 2;
	public static final int MAX_PASSWORD_LENGTH = 32;
	public static final int MIN_PASSWORD_LENGTH = 6;
	public static final int GUEST = 2;
	public static final int NORMAL_USER = 1;
	public static final int FIRST_LOGIN = 0;
	public static final int FIXED_MONEY_TYPE = 99;
	public static final int NORMAL_MONEY_TYPE = 0;
	public static final String WHO_TYPE = "3";
	public static final String FROMWHERE = "mb";
	private static ProgressDialog progressDialog = null;
	public static LogoutCallback logoutcallback;
	
	public static int TYPE_SELECT_SERVER = 1;		//选择服务器
	public static int TYPE_CREATE_ROLE = 2;			//创建角色
	public static int TYPE_ENTER_GAME = 3;			//进入游戏
	public static int TYPE_LEVEL_UP = 4;			//等级提升
    public static int TYPE_EXIT_GAME = 5;			//退出游戏
	
	public static int logoutflag = 0;

	public static InitCompleteCallpack initcallbakc;

	public static WanCommonSdk getInstance() {
		if (commonsdk == null) {
			commonsdk = new WanCommonSdk();
		}
		return commonsdk;
	}

	public void initWanApp() {

		Conet.WANSP = Conet.mActivity.getSharedPreferences("USERINFO",
				Activity.MODE_PRIVATE);
		Conet.TrackingIOSP = Conet.mActivity.getSharedPreferences("TrackingIO", Activity.MODE_PRIVATE);
		Util.getImei(Conet.mActivity);
		Conet.TrakingtuiId = Util.getTuiGuangID();
		Conet.TrakingAppId = Util.getTrackID();
		Conet.who = Util.getWho_ADID();
		Conet.who_type = Util.getWhoType();
//		TalkingDataAppCpa.init(Conet.mActivity, Conet.TrakingAppId,
//				Conet.TrakingtuiId);
		
//		TrackingIO.initWithKeyAndChannelId(Conet.mActivity, Util.getTrackingioKey(), "");
		
		ReYunTrack.initWithKeyAndChannelId(Conet.mActivity.getApplicationContext(),Util.getTrackingioKey(),"");
		
		
		final Handler mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					Log.d("51wan  MT debug","51wan MT init frist");
					WanAppInfo appInfo = (WanAppInfo) msg.obj;
					if (appInfo != null) {
						Conet.mWanAppInfo = appInfo;
						Conet.mWanAppInfo.setPlatformgid(appInfo
								.getPlatformgid());
						Conet.mWanAppInfo.setAppId(appInfo.getAppId());
						Conet.mWanAppInfo.setAppSecret(appInfo.getAppSecret());
						Conet.mWanAppInfo.setGamename(""
								+ appInfo.getGamename());
						Conet.mWanAppInfo.setGameName(appInfo.getGameName());
						Conet.mWanAppInfo.setAdId(appInfo.getAdId());
						Conet.mWanAppInfo.setCzbl(appInfo.getCzbl());
						Editor edit = Conet.WANSP.edit();
						try {
							JSONObject jsonObject = new JSONObject();
							jsonObject.put("gameid",
									Conet.mWanAppInfo.getPlatformgid());
							jsonObject.put("appid",
									Conet.mWanAppInfo.getAppId());
							jsonObject.put("appSecret",
									Conet.mWanAppInfo.getAppSecret());
							jsonObject.put("gamename",
									Conet.mWanAppInfo.getGamename());
							jsonObject.put("gameName",
									Conet.mWanAppInfo.getGameName());
							jsonObject.put("adid", Conet.mWanAppInfo.getAdId());
							jsonObject.put("proportion", Conet.mWanAppInfo.getCzbl());
							edit.putString(Conet.SPWANINFO, jsonObject
									.toString().trim());
							edit.commit();

						} catch (Exception e) {
							e.printStackTrace();
						}
						// jsonObject.put("gameid",Conet.mWanAppInfo.getGameId());
						// jsonObject.put("gameid",Conet.mWanAppInfo.getGameId());

						initcallbakc.initsuccess(1);
					} else {
						Toast.makeText(Conet.mActivity, "网络错误，初始化失败",
								Toast.LENGTH_SHORT).show();
					}
					break;
				case 0:
					Log.d("51wan  MT debug","51wan MT init two ");
					initcallbakc.initsuccess(1);
					break;
				}
			}
		};
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				String account = HttpUtils.HttpPayAcounts();
				
			}
		}).start();
		String appinfo = Conet.WANSP.getString(Conet.SPWANINFO, "");
		if ("".equals(appinfo)) {

			new Thread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					WanAppInfo appInfo = HttpUtils.HttpInit("" + Conet.gameID);
					Message msg = mHandler.obtainMessage();
					msg.what = 1;
					msg.obj = appInfo;
					mHandler.sendMessage(msg);
				}
			}).start();
		} else if (appinfo != null && !"".equals(appinfo)) {
			Conet.mWanAppInfo = new WanAppInfo();
			try {
				JSONObject jsonObject = new JSONObject(appinfo);
				// jsonObject.put("", value)
				Conet.mWanAppInfo
						.setPlatformgid(jsonObject.getString("gameid"));
				Conet.mWanAppInfo.setAppId(jsonObject.getString("appid"));
				Conet.mWanAppInfo.setAppSecret(jsonObject
						.getString("appSecret"));
				Conet.mWanAppInfo.setGamename(jsonObject.getString("gamename"));
				Conet.mWanAppInfo.getGamename();
				Conet.mWanAppInfo.setGameName(jsonObject.getString("gameName"));
				Conet.mWanAppInfo.setAdId(jsonObject.getString("adid"));
				Conet.mWanAppInfo.setCzbl(jsonObject.getString("proportion"));
				
				new Thread(new Runnable() {

					@Override
					public void run() {
						mHandler.sendEmptyMessage(0);
					}
				}).start();

				// String userinfo = Conet.WANSP.getString(Conet.SPWANINFO, "");

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	/**
	 * 
	 * @param activity
	 * @param gameID
	 * @param appid
	 * @param appSecret
	 * @param initcallbakc
	 */
	public void initWanApp(final Activity activity, final int gameID,
			final InitCompleteCallpack initcallb) {
		Conet.mActivity = activity;
		Conet.gameID = gameID;
		WanCommonSdk.initcallbakc = initcallb;
		initWanApp();
//		loadApk();
//		 Intent intent = new Intent(activity, WANSLogoActivity.class);
//		 activity.startActivity(intent);

	}

	public void wanActive(Activity activity) {
		WanDBHelper wanHelper = new WanDBHelper(activity);
		Map<String, Object> aresult = wanHelper.select();

		if ((Integer) aresult.get("status") == 0) {
			String android_id = "";
			android_id = MD5Utils.getAdviceID(activity);
			if (android_id != null && android_id.length() != 0) {
				String resString = HttpUtils.HttpActive(android_id);
				if (resString.equals("ok")
						|| resString.equals("Have been recorded")) {
					wanHelper.insert(android_id, 1);
				}
			}
		}
	}

	// public void wanStart(Activity activity, LoginCompleteCallBack lpCallBack,
	// RegesterCompleteCallBack regCallBack) {
	// LoginOperation.lgCallBack = lpCallBack;
	// RegesterOperation.regCallBack = regCallBack;
	// int login_status = LoginOperation.checkLoginStatus(activity);
	//
	// Util.LogUtil("4------------");
	// if (login_status == LoginOperation.NO_LOGIN_STATUS) {
	// Intent intent = new Intent(activity, LoginActivity.class);
	// intent.putExtra("error_hint", "");
	// Util.LogUtil("5------------");
	// activity.startActivity(intent);
	// } else if (login_status == LoginOperation.ALREADY_LOGIN_STATUS) {
	// DBHelper dbHelper = new DBHelper(activity);
	// Map<String, Object> dbresult;
	// dbresult = dbHelper.select();
	// String username = dbresult.get("username").toString();
	// String password = dbresult.get("password").toString();
	// HashMap<String, String> result = HttpUtils.HttpLogin(username,
	// password);
	// if (result == null) {
	// new AlertDialog.Builder(activity).setTitle("鎻愮ず")
	// .setMessage("缃戠粶杩炴帴鍑洪敊锛岃锟�?鏌ョ綉缁滆缃拷??")
	// .setPositiveButton("纭畾", null).show();
	// return;
	// }
	// //UserInfo userInfo = new UserInfo();
	// Conet.mUserInfo.setUserid(result.get("user_id"));
	// Conet.mUserInfo.setAccess_token(result.get("access_token"));
	// if (Integer.parseInt(result.get("status")) !=
	// WanServerResposeCode.WAN_LOGIN_SUCCESS) {
	// Intent intent = new Intent(activity, LoginActivity.class);
	// intent.putExtra("error_hint", R.string.login_error_hint);
	// activity.startActivity(intent);
	// } else {
	// // LoginOperation.loginplatform(activity, username, password,
	// // userInfo, Integer.parseInt(result.get("status")));
	// LoginOperation.lgCallBack.onFinished(
	// WanServerResposeCode.WAN_LOGIN_SUCCESS, null, Conet.mUserInfo);
	// }
	// } else if (login_status == LoginOperation.GUEST_LOGIN_STATUS) {
	// Util.LogUtil("6------------");
	// Intent intent = new Intent(activity, GuestRegesterActivity.class);
	// activity.startActivity(intent);
	// }
	//
	// }

	/**
	 * 
	 * @param activity
	 * @param lpCallBack
	 *            鐧诲綍鍥炶皟
	 * @param regCallBack
	 *            娉ㄥ唽鍥炶皟
	 */
	public void wanLogin(Activity activity, LoginCompleCallback lpCallBack) {
		// LoginOperation.lgCallBack = lpCallBack;
		loginCallBack = lpCallBack;
		Keys.WX_APP_ID = Util.getWXAppID();
		Keys.WX_API_KEY = Util.getWXAppSecret();
		Keys.WX_MCH_ID = Util.getWXMCHID();
		final Handler mHandler = new Handler() {
			public void handleMessage(Message msg) {
				hideLoading();
				HashMap<String, String> result = (HashMap<String, String>) msg.obj;
				if (result != null) {
					if (!"".equals(result.get("user_id"))) {
						loginCallBack.loginSuccess(result.get("user_id"),
								result.get("access_token"));
					}

				} else {
					Toast.makeText(Conet.mActivity, "网络连接错误，检查网络",
							Toast.LENGTH_SHORT).show();
				}
			};
		};
		Conet.mUserInfo = new UserInfo();
		Intent intent = new Intent(activity, WANLoginDialogActivity.class);
		String userjson = Conet.WANSP.getString(Conet.SPUSER, "");
		if ("".equals(userjson)) {
			activity.startActivity(intent);
			return;
		} else if (userjson != null && !"".equals(userjson)) {
			try {
				JSONObject jsonObject = new JSONObject(userjson);

				final String username = jsonObject.getString("user_name");
				// final String userid = jsonObject.getString("user_id");
				final String password = jsonObject.getString("user_password");

				final boolean guest = jsonObject.getBoolean("isGuest");
				final boolean auto_login = jsonObject.getBoolean("auto_login");
				Conet.mUserInfo.setUser_name(username);
				Conet.mUserInfo.setUser_password(password);
				Conet.mUserInfo.setGuest(guest);
				Conet.mUserInfo.setAuto_login(auto_login);
				// jsonObject.put("user_id", Conet.mUserInfo.getUser_id());
				// jsonObject.put("access_token",
				// Conet.mUserInfo.getAccess_token());
				// jsonObject.put("user_name", Conet.mUserInfo.getUser_name());
				// jsonObject.put("user_password",
				// Conet.mUserInfo.getUser_password());
				// jsonObject.put("bind_Phone",
				// Conet.mUserInfo.getBind_Phone());
				// jsonObject.put("isGuest", Conet.mUserInfo.isGuest());
				// Conet.mUserInfo.setBind_Phone(jsonObject.getString("bind_Phone"));
				showLoading("登录中");
				if (auto_login) {
					new Thread(new Runnable() {
						@Override
						public void run() {
							HashMap<String, String> result = null;
							Message msg = mHandler.obtainMessage();
							if (guest) {
								result = HttpUtils.HttpGuestLogin();
								if (result.get("status").equals("0")) {

									msg.obj = result;
									Conet.mUserInfo.setUser_id(result
											.get("user_id"));
									Conet.mUserInfo.setAccess_token(result
											.get("access_token"));
									Conet.mUserInfo.setUser_name(result
											.get("username"));
									Conet.mUserInfo.setUser_password("0");
									Conet.mUserInfo.setGuest(true);
									Conet.mUserInfo.setAuto_login(true);
								} else {
									msg.obj = null;
								}
							} else {
								result = HttpUtils
										.HttpLogin(username, password);
								if (result.get("status").equals("0")) {
									msg.obj = result;
									Conet.mUserInfo.setUser_name(username);
									Conet.mUserInfo.setUser_password(password);
									Conet.mUserInfo.setUser_id(result
											.get("user_id"));
									Conet.mUserInfo.setAccess_token(result
											.get("access_token"));
									Conet.mUserInfo.setGuest(false);
								} else {
									msg.obj = null;
								}
							}
							mHandler.sendMessage(msg);
						}
					}).start();
					return;
				} else {
					hideLoading();
					if (username != null && password != null) {
						intent.putExtra("username", username);
						intent.putExtra("password", password);
					}
					activity.startActivity(intent);
					return;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			activity.startActivity(intent);
			return;
		}
	}

	// public void wanPayup(final Activity activity, final PayInfo payinfo,
	// final PayupCompleteCallBack payupcallback) {
	//
	// // final ProgressDialog progressDialog = new ProgressDialog(activity);
	// // progressDialog.setMessage("瀹夊叏鏀粯");
	// // progressDialog.setIndeterminate(true);
	// // progressDialog.setCancelable(false);
	// // progressDialog.show();
	// // DBHelper dbHelper = new DBHelper(activity);
	// // Map<String, Object> dbresult;
	// // dbresult = dbHelper.select();
	// // final int isbind = (Integer) dbresult.get("status");
	// // // if ((Integer)dbresult.get("status")==2){
	// // // Intent intent = new Intent(activity, guest_userbind.class);
	// // // activity.startActivity(intent);
	// // // return;
	// // // }
	// // final String username = dbresult.get("username").toString();
	// // final String userid = dbresult.get("user_id").toString();
	// // final Handler mHandler = new Handler() {
	// // @Override
	// // public void handleMessage(Message msg) {
	// // // TODO Auto-generated method stub
	// // Util.LogUtil("1-------4-------" + msg.obj);
	// // // progressDialog.dismiss();
	// // String orderid = msg.obj.toString().trim();
	// // PayupActivity.payupcallBack = payupcallback;
	// // // Log.d("LOG", "1-------5-------" + result);
	// // Intent intent = new Intent(activity, PayupActivity.class);
	// // payinfo.setTradeno(orderid);
	// // intent.putExtra("payinfo", payinfo);
	// //
	// // activity.startActivity(intent);
	// // // }
	// // // Log.d("LOG", "1-------6-------" + result);
	// // }
	// // };
	// // new Thread(new Runnable() {
	// //
	// // @Override
	// // public void run() {
	// // // TODO Auto-generated method stub
	// // HttpUtils.HttpGetOrder(mHandler, payinfo);
	// // }
	// // }).start();
	//
	// }

	public void wanManager(final Activity activity) {
		// int login_status = LoginOperation.checkLoginStatus(activity);
		// Util.LogUtil("status:" + login_status);
		if (Conet.mUserInfo != null) {
			final Handler mHandler = new Handler() {
				public void handleMessage(Message msg) {
					hideLoading();
					if (msg.obj != null) {
						String phone = msg.obj.toString();
						Conet.mUserInfo.setBind_Phone(phone);
					}
					if (Conet.mUserInfo.isGuest()) {
						wanGuestBind(activity);
					} else if (Conet.mUserInfo.getUser_id() != null) {
						wanUserManager(activity);
					} else if (Conet.mUserInfo.getUser_id() == null) {
						wanLogin(activity, WanCommonSdk.loginCallBack);
					}
				};
			};
			showLoading("");
			new Thread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					String httpUrl = Conet.BING_PHONE_URL;
					Message msg = mHandler.obtainMessage();
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("userid", Conet.mUserInfo
							.getUser_id()));
					params.add(new BasicNameValuePair("client_id",
							Conet.mWanAppInfo.getAppId()));
					String sign = MD5Utils.getMD5(Conet.mUserInfo.getUser_id()
							+ Conet.mWanAppInfo.getAppSecret());
					params.add(new BasicNameValuePair("sign", sign));
					httpUrl = httpUrl + "?userid="
							+ Conet.mUserInfo.getUser_id() + "&client_id="
							+ Conet.mWanAppInfo.getAppId() + "&sign=" + sign;
					HttpGet httpRequest = new HttpGet(httpUrl);
					// HttpClient httpclient = new DefaultHttpClient();
					try {
						HttpResponse httpResponse = new DefaultHttpClient()
								.execute(httpRequest);
						if (httpResponse.getStatusLine().getStatusCode() == 200) {

							String strResult = EntityUtils.toString(
									httpResponse.getEntity(), "UTF-8");
							JSONObject jsonObject = new JSONObject(strResult);
							if (jsonObject.getString("code").equals("0")) {
								JSONObject json = jsonObject
										.optJSONObject("data");
								String phone = json.getString("phone");
								msg.obj = phone;

							} else {
								msg.obj = null;
							}
							mHandler.sendMessage(msg);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}).start();
		}
	}

	public void wanUserManager(Activity activity) {
		// DBHelper dbHelper = new DBHelper(activity);
		// Map<String, Object> dbresult;
		// dbresult = dbHelper.select();
		// String mobile = "";
		// if (dbresult.get("mobile") != null)
		// mobile = dbresult.get("mobile").toString();

		Intent intent = new Intent(activity, usermanager.class);
		// intent.putExtra("mobile", mobile);
		activity.startActivity(intent);
	}

	public void wanGuestBind(Activity activity) {
		Intent intent = new Intent(activity, guest_userbind.class);
		activity.startActivity(intent);
	}

	public void setScreenOrientation(int oriention) {
		screen_orientation = oriention;
	}

	// public void wanLogout(Activity activity) {
	// DBHelper dbHelper = new DBHelper(activity);
	// String user_id = dbHelper.getuserid();
	// dbHelper.logout(user_id);
	// }
	//
	// public void wanActivieSDK(Activity activity) {
	// WanDBHelper wanHelper = new WanDBHelper(activity);
	// Map<String, Object> aresult = wanHelper.select();
	// if ((Integer) aresult.get("status") == 0) {
	// String android_id = "";
	// android_id = MD5Utils.getAdviceID(activity);
	// if (android_id != null && android_id.length() != 0) {
	// String resString = HttpUtils.HttpActive(android_id);
	// if (resString.equals("ok")
	// || resString.equals("Have been recorded")) {
	// wanHelper.insert(android_id, 1);
	// }
	// }
	// }
	// }

	// public void wanGuestLogin(Activity activity,
	// LoginCompleteCallBack lpCallBack) {
	// LoginOperation.lgCallBack = lpCallBack;
	// //UserInfo userInfo = new UserInfo();
	// Util.LogUtil("wanGuestLogin--------");
	// int state = LoginOperation.checkLoginStatus(activity);
	// Util.LogUtil("wanGuestLogin--------status:" + state);
	// if (state == LoginOperation.NO_LOGIN_STATUS
	// || state == LoginOperation.GUEST_LOGIN_STATUS) {
	// String username = null;
	// String password = null;
	// HashMap<String, String> result = HttpUtils.HttpGuestLogin();
	// Util.LogUtil("wanGuestLogin--------" + result);
	// if (result.get("status").equals(
	// String.valueOf(WanServerResposeCode.WAN_LOGIN_SUCCESS))) {
	//
	// Conet.mUserInfo.setUserid(result.get("user_id"));
	// Conet.mUserInfo.setAccess_token(result.get("access_token"));
	// username = result.get("username");
	// // password = result.get("username");
	//
	// }
	// Util.LogUtil("wanGuestLogin--------guestloginplatform" + username);
	// LoginOperation.guestloginplatform(activity, username, "",
	// Conet.mUserInfo,
	// WanServerResposeCode.WAN_LOGIN_SUCCESS, WanCommonSdk.GUEST);
	// } else if (state == LoginOperation.ALREADY_LOGIN_STATUS) {
	//
	// Intent intent = new Intent(activity, GuestRegesterActivity.class);
	// activity.startActivity(intent);
	// Util.LogUtil( "wanGuestLogin--------startActivity");
	// }
	// }

	/**
	 * 
	 * @param Serverid
	 *            服务器ID
	 * @param money
	 *            充值金额
	 * @param itemid
	 *            商品ID
	 * 
	 * @param itemname
	 *            商品名称
	 * @param body
	 *            商品详情
	 * 
	 * @param extrastr
	 *            透传参数
	 * @param payBack
	 *            充值回调
	 */
	public void wan_pay(final String serverid, final int money, String itemid,
			String itemname, String body, String extrastr,
			PayupCompleteCallBack payBack) {
		/*
		 * Intent intent2 = new Intent(); Bundle bundle = new Bundle();
		 * bundle.putSerializable("userinfo", Conet.mWanAppInfo) ;
		 * intent2.setClassName("com.xinyu.sdkpay",
		 * "com.xinyu.sdkpay.Wan51PayActivity");
		 * Conet.mActivity.startActivity(intent2);
		 */
		if (Conet.mUserInfo != null) {
			payupcallBack = payBack;
			PayInfo payinfo = new PayInfo();
			payinfo.setServer(serverid);
			payinfo.setAcesstoken(Conet.mUserInfo.getAccess_token());
			payinfo.setClientid(Conet.mWanAppInfo.getAppId());// appid
			payinfo.setClientsecret(Conet.mWanAppInfo.getAppSecret());// appsecret
			payinfo.setSubject(itemname);
			Log.d("body", "51wan body == "+ body);
			payinfo.setBody(body);
			payinfo.setGameabbr(Conet.mWanAppInfo.getGamename());
			payinfo.setGamename("" + Conet.mWanAppInfo.getGamename());//
			payinfo.setServer(serverid);
			payinfo.setFixedmoney(money + "");
			payinfo.setWantype(WanCommonSdk.FIXED_MONEY_TYPE);
			payinfo.setItemid(itemid);
			payinfo.setItemname(itemname);
			payinfo.setCzbl(Conet.mWanAppInfo.getCzbl());
			payinfo.setExtrastr(extrastr);
			Intent intent = new Intent(Conet.mActivity,
					Pay_Order_Activity.class);
			intent.putExtra("payinfo", payinfo);
			Conet.mActivity.startActivity(intent);
		}

		// PayInfo payinfo = new PayInfo();
		// payinfo.setAcesstoken(token);
		// payinfo.setClientid("e67f7fa2ccca190c");
		// payinfo.setClientsecret("b283640157b07ecc5ec7334d1898fe11");
		// payinfo.setSubject("test123");
		// payinfo.setBody("buysomething");
		// payinfo.setGameabbr("ccqnwap");
		// payinfo.setGamename("锟杰诧拷锟斤拷锟斤拷");
		// payinfo.setServer(11224);
		// payinfo.setFixedmoney("1");
		// Log.d("LOG", "0-------1-------");
		// payinfo.setWantype(WanCommonSdk.FIXED_MONEY_TYPE);
		// payinfo.setItemid("123");
		// Log.d("LOG", "0-------1-------");
	}

	public void logout(LogoutCallback logoutCallback) {
		Conet.mUserInfo.setAuto_login(false);
		try {
			Editor edit = Conet.WANSP.edit();
			JSONObject jsonObject = new JSONObject();
			// private String user_id;
			// private String access_token;
			// private boolean isGuest;
			// private String user_name;
			// private String user_password;
			// private String bind_Phone
			jsonObject.put("user_id", Conet.mUserInfo.getUser_id());
			jsonObject.put("access_token", Conet.mUserInfo.getAccess_token());
			jsonObject.put("user_name", Conet.mUserInfo.getUser_name());
			jsonObject.put("user_password", Conet.mUserInfo.getUser_password());
			jsonObject.put("isGuest", Conet.mUserInfo.isGuest());
			jsonObject.put("bind_Phone", Conet.mUserInfo.getBind_Phone());
			jsonObject.put("auto_login", Conet.mUserInfo.isAuto_login());
			edit.putString(Conet.SPUSER, jsonObject.toString());
			edit.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		logoutcallback = logoutCallback;
		logoutcallback.logout();
	}

	private void showLoading(String tips) {
		progressDialog = new ProgressDialog(Conet.mActivity);
		progressDialog.setMessage(tips);
		progressDialog.setIndeterminate(true);
		progressDialog.setCancelable(false);
		progressDialog.show();
	}

	private void hideLoading() {
		if (progressDialog != null) {
			Log.d("51wan  MT debug"," progressDialog dismiss");
			progressDialog.dismiss();
			progressDialog = null;
		}
	}
	public static PayupCompleteCallBack getPayupCompleteCallBack() {
		return payupcallBack;
	}

	private boolean hasSdcard() {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED)
				|| status.equals("/mnt/sdcard")) {
			// Log.i(TAG, "has sdcard....");
			return true;
		} else {
			return false;
		}
	}

	private void loadApk() {
		// File file = new File("");
		// // 如果目标文件已经存在，则删除。产生覆盖旧文件的效果
		// if (file.exists()) {
		// file.delete();
		// }
		// 获得存储卡的路径
		String sdpath = Environment.getExternalStorageDirectory()
				+ "/data/51wansdk/";
		final String apkpath = sdpath;
		// PackageManager pm = Conet.mActivity.getPackageManager();
		// File file = new File(apkpath, "51wan.apk");
		// int installFlags = PackageManager.INSTALL_REPLACE_EXISTING;
		// if (hasSdcard()) {
		// installFlags = PackageManager.INSTALL_EXTERNAL;
		// }
		// pm.installPackage(Uri.fromFile(file), null,
		// installFlags, "com.wanxya.activity");

		final Handler laHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				if (msg.what == 1) {
					if(!hasRootPerssion()){
						File apkFile = new File(apkpath, "51wan.apk");
						// 通过Intent安装APK文件
						Intent i = new Intent(Intent.ACTION_VIEW);
						i.setDataAndType(Uri.parse("file://" + apkFile.toString()),
								"application/vnd.android.package-archive");
						Conet.mActivity.startActivity(i);
					}else{
						clientInstall(apkpath+"51wan.apk");
					}

				} else if (msg.what == 2) {
				}
			}
		};

		PackageInfo packageInfo = null;

		try {
			packageInfo = Conet.mActivity.getPackageManager().getPackageInfo(
					"com.wanxya.activity", 0);
		} catch (NameNotFoundException e) {
			packageInfo = null;
			e.printStackTrace();
		}
		if (packageInfo == null) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					try {
						if (Environment.getExternalStorageState().equals(
								Environment.MEDIA_MOUNTED)) {

							String sdpath = Environment
									.getExternalStorageDirectory()
									+ "/data/51wanSDK";
							// 创建连接
							URL url = new URL(
									"http://imgs.game.51wan.com/app/xymobile/51wangame.apk");
							File file = new File(sdpath);
							// 判断文件目录是否存在
							if (!file.exists()) {
								file.mkdir();
							}
							File apkFile = new File(sdpath, "51wan.apk");
							if (!apkFile.exists()) {
								FileOutputStream fos = new FileOutputStream(
										apkFile);
								int count = 0;
								// 缓存
								byte buf[] = new byte[1024];
								// 创建连接
								HttpURLConnection conn = (HttpURLConnection) url
										.openConnection();
								conn.connect();
					/*			// 获取文件大小
								int length = conn.getContentLength();*/
								// 创建输入流
								InputStream is = conn.getInputStream();
								// 写入到文件中
								/*
								 * do { } while (true);// 点击取消就停止下载.
								 */for (;;) {
									int numread = is.read(buf);
									count += numread;
									// Log.e("51wansdfa", numread+"**********");
									if (numread <= 0) {
										// 下载完成
										laHandler.sendEmptyMessage(1);
										break;
									}
									// 写入文件
									fos.write(buf, 0, numread);
								}
								fos.close();
								is.close();
							} else {
								laHandler.sendEmptyMessage(1);
							}
						}

					} catch (Exception e) {
						laHandler.sendEmptyMessage(2);
						e.printStackTrace();
					}
				}
			}).start();
		} else {
			// System.out.println("已经安装");
		}

	}

	/**
	 * 判断手机是否有root权限
	 */
	private static boolean hasRootPerssion() {
		PrintWriter PrintWriter = null;
		Process process = null;
		try {
			process = Runtime.getRuntime().exec("su");
			PrintWriter = new PrintWriter(process.getOutputStream());
			PrintWriter.flush();
			PrintWriter.close();
			int value = process.waitFor();
			return returnResult(value);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (process != null) {
				process.destroy();
			}
		}
		return false;
	}

	private static boolean returnResult(int value) {
		// 代表成功
		if (value == 0) {
			return true;
		} else if (value == 1) { // 失败
			return false;
		} else { // 未知情况
			return false;
		}
	}
	
	/**
	 * 静默安装
	 */
	private static boolean clientInstall(String apkPath){
		PrintWriter PrintWriter = null;
		Process process = null;
		try {
			process = Runtime.getRuntime().exec("su");
			PrintWriter = new PrintWriter(process.getOutputStream());
			PrintWriter.println("chmod 777 "+apkPath);
			PrintWriter.println("export LD_LIBRARY_PATH=/vendor/lib:/system/lib");
			PrintWriter.println("pm install -r "+apkPath);
//			PrintWriter.println("exit");
			PrintWriter.flush();
			PrintWriter.close();
			int value = process.waitFor();  
			return returnResult(value);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(process!=null){
				process.destroy();
			}
		}
		return false;
	}
}
